package com.right.health.app.ui.me;

import android.app.Activity;
import android.graphics.Color;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.magic.basic.utils.CollectionUtil;
import com.magic.basic.utils.DisplayUtil;
import com.right.health.app.bean.AreaBean;
import com.right.health.app.net.UserApi;
import com.right.health.app.utils.SoftInputUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author weming
 * @Date 2021/3/29
 * @description 所有地区选择
 */
public class AllAreaUIUtil {
    private static AllAreaUIUtil mInstance;

    //  省
    private List<AreaBean> options1Items = new ArrayList<>();
    //  市
    private List<List<AreaBean>> options2Items = new ArrayList<>();
    //  区
    private List<List<List<AreaBean>>> options3Items = new ArrayList<>();

    private Map<Integer, Integer> mProvinceMap = new HashMap<>();//省份id对应的省份列表中的索引

    private Map<Integer, String> mCityMap = new HashMap<>();//城市id对应的城市列表中的索引

    private int showIndex1, showIndex2, showIndex3;

    private ResultCallback mCallback;

    private AllAreaUIUtil() {
    }

    public static AllAreaUIUtil getInstance() {
        if (mInstance == null) {
            synchronized (AllAreaUIUtil.class) {
                if (mInstance == null) {
                    mInstance = new AllAreaUIUtil();
                }
            }
        }
        return mInstance;
    }

    boolean isDataEmpty() {
        return CollectionUtil.isEmpty(options1Items);
    }

    void showDialog(Activity activity, ResultCallback resultCallBack) {
        mCallback = resultCallBack;
        if (!CollectionUtil.isEmpty(options1Items)) {
            showPickerView(activity);
        } else {
            getData(activity, true);
        }
    }


    void getData(Activity activity, boolean isShow) {
        UserApi userApi = new UserApi();
        userApi.setListener((request, response) -> {
            try {
                JSONObject jsonObject = new JSONObject(response.data);
                String data = jsonObject.optString("areas");
                List<AreaBean> list = new Gson().fromJson(data, new TypeToken<List<AreaBean>>() {
                }.getType());
                if (!CollectionUtil.isEmpty(list)) {
                    parseData(list);
                    if (isShow && !CollectionUtil.isEmpty(options1Items)) {
                        showPickerView(activity);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
//                ToastUtil.show(activity, "数据解析失败");
            }
        });
        userApi.getAllArea();
    }

    void getContent(int id1, int id2, int id3, ResultCallback callback) {
        if (!CollectionUtil.isEmpty(options1Items)) {
            searchContent(id1, id2, id3, callback);
        } else {
            UserApi userApi = new UserApi();
            userApi.setListener((request, response) -> {
                try {
                    JSONObject jsonObject = new JSONObject(response.data);
                    String data = jsonObject.optString("areas");
                    List<AreaBean> list = new Gson().fromJson(data, new TypeToken<List<AreaBean>>() {
                    }.getType());
                    if (!CollectionUtil.isEmpty(list)) {
                        parseData(list);
                        if (!CollectionUtil.isEmpty(options1Items)) {
                            searchContent(id1, id2, id3, callback);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
//                ToastUtil.show(activity, "数据解析失败");
                }
            });
            userApi.getAllArea();
        }
    }

    private void searchContent(int id1, int id2, int id3, ResultCallback callback) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < options1Items.size(); i++) {
            if (options1Items.get(i).getAreasid() == id1) {
                stringBuilder.append(options1Items.get(i).getAreaname()).append(" ");
                showIndex1 = i;
                List<AreaBean> cityList = options1Items.get(i).getChildList();
                for (int j = 0; j < cityList.size(); j++) {
                    if (cityList.get(j).getAreasid() == id2) {
                        stringBuilder.append(cityList.get(j).getAreaname()).append(" ");
                        showIndex2 = j;
                        List<AreaBean> areaList = cityList.get(j).getChildList();
                        for (int k = 0; k < areaList.size(); k++) {
                            if (areaList.get(k).getAreasid() == id3) {
                                stringBuilder.append(areaList.get(k).getAreaname());
                                showIndex3 = k;
                                if (callback != null) {
                                    callback.onSearch(stringBuilder.toString());
                                }
                            }
                        }
                    }
                }
            }
        }

    }


    /**
     * 解析数据并组装成自己想要的list
     */
    private void parseData(List<AreaBean> allList) {

        try {
            Collections.sort(allList, (o1, o2) -> o1.getRegiontype() - o2.getRegiontype());
            for (AreaBean areaBean : allList) {
                if (areaBean.getRegiontype() == 1) {
                    options1Items.add(areaBean);
                    mProvinceMap.put(areaBean.getAreasid(), options1Items.size() - 1);
                } else if (areaBean.getRegiontype() == 2) {
                    if (mProvinceMap.containsKey(areaBean.getParentid())) {
                        int index = mProvinceMap.get(areaBean.getParentid());
                        options1Items.get(index).getChildList().add(areaBean);
                        mCityMap.put(areaBean.getAreasid(), index + "," + (options1Items.get(index).getChildList().size() - 1));
                    }
                } else if (areaBean.getRegiontype() == 3) {
                    if (mCityMap.containsKey(areaBean.getParentid())) {
                        String str = mCityMap.get(areaBean.getParentid());
                        String[] indexArr = str.split(",");
                        options1Items.get(Integer.parseInt(indexArr[0])).getChildList()
                                .get(Integer.parseInt(indexArr[1])).getChildList().add(areaBean);

                    }
                }
            }

            for (int i = 0; i < options1Items.size(); i++) {
                //存放城市
                List<AreaBean> cityList = new ArrayList<>();
                //存放区
                List<List<AreaBean>> province_AreaList = new ArrayList<>();
                cityList.addAll(options1Items.get(i).getChildList());
                /**
                 * 添加城市数据
                 */
                options2Items.add(cityList);
                for (int j = 0; j < cityList.size(); j++) {
                    province_AreaList.add(cityList.get(j).getChildList());
                }
                options3Items.add(province_AreaList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 展示选择器
     */
    private void showPickerView(Activity activity) {// 弹出选择器
        SoftInputUtil.hideSoftInputMode(activity, activity.getCurrentFocus());
        OptionsPickerView pvOptions = new OptionsPickerBuilder(activity, (options1, options2, options3, v) -> {
            //返回的分别是三个级别的选中位置
            try {
                String tx = options1Items.get(options1).getAreaname() + " " +
                        options2Items.get(options1).get(options2).getAreaname() + " " +
                        options3Items.get(options1).get(options2).get(options3).getAreaname();
                showIndex1 = options1;
                showIndex2 = options2;
                showIndex3 = options3;
                if (mCallback != null) {
                    mCallback.onSelected(tx, options1Items.get(options1).getAreasid(), options2Items.get(options1).get(options2).getAreasid()
                            , options3Items.get(options1).get(options2).get(options3).getAreasid());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(DisplayUtil.dip2px(activity, 7))
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.setSelectOptions(showIndex1, showIndex2, showIndex3);
        pvOptions.show();
    }

    interface ResultCallback {
        void onSelected(String content, int provinceId, int cityId, int areaId);

        void onSearch(String content);
    }

}
